package com.team_project.boot.controller;

import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager;
import com.team_project.boot.entity.Auther;
import com.team_project.boot.mapper.AuctherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class AutherController {

    @Value("${imagePath}")
    private String imagePath;
    @Autowired(required = false)
    AuctherMapper mapper;
    @RequestMapping("/author")
    public List<Auther> selectAll(){
        return mapper.selectAll();
    }
    @RequestMapping("/addAuther")
    public void addAuther(Auther auther, MultipartFile file){
        System.out.println("auther = " + auther + ", file = " + file);

        String fileName = file.getOriginalFilename();
        String suixx = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suixx;
        SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
        /*创建表示当前时间的日期对象*/
        Date date = new Date();
        //得到日期路径
        String datePath = f.format(date);
        String path = imagePath+datePath;
        File dir = new File(path+fileName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(path+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = datePath+fileName;
        auther.setUrl(url);
        mapper.insert(auther);
    }

    @RequestMapping("/selectAuther")
    public List<Auther> selectAuther(){
        return mapper.selectAll();
    }

    @RequestMapping("/deleteByid")
    public void deleteByid(Integer id){
        mapper.deleteByid(id);
    }

    @RequestMapping("/selectByLimit")
    public List<Auther> selectByLimit(){
        return mapper.selectAll();
    }
}
